<template>
  <div class="tables-main">  
    <div class="table-box">
      <!-- <div class="timeType">
        <span class="titles">类型:</span>
        <el-select v-model="upfileInfo.templateId" placeholder="选择类型" @change="changeTem">
          <el-option v-for="item in pathList"  :key="item.templateType" :label="item.templateType" :value="item.templateId" />
        </el-select>
       </div> -->
      <div class="down-bth" v-if="userRole.userRole!='1'">
        <el-button type="primary" icon="UploadFilled" @click= "downSome">导入报表</el-button>
        <muban class="downMu" :templateType="downType" />
      </div>
      <el-table
        style="width: 90%;margin: 10px auto"
        :data="tableData"
         border
        :header-cell-style="{
          background: '#E7F2FF',
          color: 'black',
        }"
         :tooltip-options="{
           enterable: true, placement: 'right', showArrow: true, hideAfter: 200, popperOptions: { strategy: 'fixed' }
      }"
        v-loading="loading" 
      >
      <el-table-column prop="val" label="期别" width="150" align="center"/>
      <el-table-column label="报表状态" width="150"       align="center">
        <template #default="scope" v-if="userRole.userRole!='3'">
          {{ typeForm[scope.row.rState == '2'&& scope.row.checkInfoList[0].shState == 2?'5':scope.row.rState] }}
        </template>
        <template #default="scope" v-else>
          {{ typeForm[scope.row.rState] }}
        </template>
      </el-table-column>  
        <el-table-column prop="templateType" label="报表类型" width="160" show-overflow-tooltip align="center"/>
        <el-table-column label="是否超时" width="100">
        <template #default="scope">
          {{ scope.row.notice? '已超时' : '未超时' }}
        </template>
        </el-table-column>
        <el-table-column prop="developArea" label="填报人" width="180" align="center"/>
        <el-table-column prop="checkTime" label="审核时间" width="180" align="center"/>
        <el-table-column prop="reportTime" label="上报时间" width="180" align="center"/>
        <el-table-column label="操作" min-width="180" width="auto" fixed="right" align="center" >
          <template #default="scope"> 
            <!-- <el-button v-if="userRole.userRole!='1'&&scope.row.rState == '1'" link type="primary" size="small" @click="getReport(scope.row)">上报</el-button> -->
            <el-button v-if="userRole.userRole!='1'" link type="primary" size="small" @click="editReport(scope.row)">报表修改</el-button>
            <el-button  link type="primary" size="small" @click="downReports(scope.row)">报表导出</el-button>
            <!-- <el-button link type="primary" size="small" @click="returnReport(scope.row, '1')"
            v-if="scope.row.rState == '2'&& userRole.userRole=='1'">通过</el-button>
          <el-button link type="primary" size="small" @click="returnReport(scope.row, '2')" style="color: red;"
            v-if="userRole.userRole=='1'&&scope.row.rState != '1'">退回</el-button> -->
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination-box">
      <el-pagination
    :total="totals"
    layout="prev, pager, next"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange" 
  />
    </div>
  </div>
  <div class="showBox" v-if="showSuccess">
    <img src="../../assets/images/Check-Circle-Fill.png" alt="">
    <span>填报成功</span>
  </div>
  <el-dialog v-model="upShow" title="导入报表" width="50%">
    <el-form :model="upfileInfo" label-width="100px" ref="ruleFormRef"
    :rules="rules">
    <el-form-item label="填报人" prop="developArea">
      <el-input v-model="upfileInfo.developArea" disabled autocomplete="off" style="width: 214px;" />
    </el-form-item>
    <el-form-item label="报表类型" prop="templateId" v-if="form.templateType=='招商引资'">
        <el-select v-model="upfileInfo.templateId" placeholder="选择类型" @change="changeTem">
          <el-option v-for="item in pathList"  :key="item.templateType" :label="item.templateType" :value="item.templateId" />
        </el-select>
      </el-form-item>
    <el-form-item label="报表期别"  prop="year" v-if="upfileInfo.templateId">
      <div class="data-check">
       <el-date-picker
        v-model="upfileInfo.year"
        placeholder="时间"
        style="width: 214px;margin-right: 20px;"
        :format="upfileInfo.templateId=='8'?'YYYY年MM月':'YYYY年'"
        :type="upfileInfo.templateId=='8'?'month':'year'"
        :value-format="upfileInfo.templateId=='8'?'YYYY年MM月':'YYYY年'"
        @change = "dataChange"
      />
      </div> 
    </el-form-item>
    <el-form-item label="季度" prop="week" v-if="upfileInfo.templateId!='8'">
      <el-select v-model="upfileInfo.week" placeholder="选择季度" @change="changeWeek">
        <el-option label="第1季度" value="第1季度" />
        <el-option label="第2季度" value="第2季度" />
        <el-option label="第3季度" value="第3季度" />
        <el-option label="第4季度" value="第4季度" />
      </el-select>
    </el-form-item>
    <el-form-item label="报表上传" prop="file">
      <el-upload
        ref="upload"
        class="upload-demo"
        action=""
        :limit="1"
        :on-exceed="handleExceed"
        :auto-upload="false"
        :on-change = "getFile"
       >
  <template #trigger>
    <el-button type="info">选择文件</el-button>
  </template>
  <template #tip>
    <div class="el-upload__tip text-red">
      只能上传一个，继续上传将会覆盖
    </div>
  </template>
</el-upload>
    </el-form-item>
  </el-form>
  <template #footer>
    <span class="dialog-footer">
      <el-button @click="upShow=false">取消</el-button>
      <el-button type="danger" @click="submitForm(ruleFormRef)">
        确定
      </el-button>
    </span>
  </template>
</el-dialog>
<el-dialog v-model="editShow" title="修改报表" width="50%">
    <el-form :model="editInfo" label-width="100px" ref="ruleFormRefs"
    :rules="rules">
    <el-form-item label="报表名称">
      <el-input v-model="editInfo.name" disabled autocomplete="off" style="width: 100%;" />
    </el-form-item>
    <el-form-item label="报表上传" prop="files">
      <el-upload
        ref="upload"
        class="upload-demo"
        action=""
        :limit="1"
        :on-exceed="handleExceed"
        :auto-upload="false"
        :on-change = "getFile"
       >
  <template #trigger>
    <el-button type="info">选择文件</el-button>
  </template>
  <template #tip>
    <div class="el-upload__tip text-red">
      只能上传一个，继续上传将会覆盖
    </div>
  </template>
</el-upload>
    </el-form-item>
  </el-form>
  <template #footer>
    <span class="dialog-footer">
      <el-button @click="editClear">取消</el-button>
      <el-button type="danger" @click="editSure()">
        确定
      </el-button>
    </span>
  </template>
</el-dialog>
<el-dialog v-model="returnShow" title="退回" width="30%">
    <span>原因：</span><el-input v-model="returnInfo.reason" autocomplete="off" style="width: 300px" />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="returnShow = false">取消</el-button>
        <el-button type="primary" @click="sureReturn">
          退回
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ref, onMounted ,reactive,watch} from 'vue'
import { reportFindList,findListS ,reportpublish,addimports,editeReport,reportcheck} from "@/util/api";
import { useRouter } from "vue-router";
import muban from '@/components/muban.vue';
import { ElMessage, genFileId ,ElMessageBox } from 'element-plus'
import { useStore } from '@/store'
import type { UploadInstance, UploadProps, UploadRawFile,FormInstance } from 'element-plus'
const upload = ref<UploadInstance>()
const userRole = useStore().state.userInfo
const ruleFormRef = ref<FormInstance>()
const downType = ref("")
//路由
const router = useRouter();
//筛选显示的报表类型
const pathList: any = ref([
  {
    templateId:"8",
    templateType:"月报"
  },
  {
    templateId:"10",
    templateType:"季报"
  },
])
//报表请求参数
const form: any =ref({
          checkUserId:'',
          createUserId:'',
          developArea:'',
          rState:'',
          reportTimeEnd:'',
          reportTimeStart:'',
          state:'1',
          templateType:'',
          val:'',
          currentPage: 1, //第几页
          pageNum: 10, //一页几个
    }) 
//报表上传参数
const upfileInfo:any = ref({
   developArea:'',
   templateId:"",
   val:"",
   week:"",
   files:"",
   year:""
})
//退回窗口
const returnShow: any = ref(false)
//报表修改参数
const editInfo:any=ref({
id:"",
name:"",
files:""
})
//报表状态
const typeForm: any = ref({
  '1': '未上报',
  '2': '未审批',
  '4': '已退回',
  '5': '已审批'
})
upfileInfo.value.developArea = userRole.develop
//总条数   
const totals:any = ref(0)
//报表数据     
const tableData:any = ref([])         
//等待
const loading:any = ref(false)
//展示录入报表
const upShow:any = ref(false)
const editShow:any = ref(false)

//上报成功展示      
const showSuccess: any = ref(false) 
const downReports = (item:any)=>{
if(item.file==null)return ElMessage.error('无报表')

let  flieitem = JSON.parse(item.file)[0]
console.log(flieitem)
let link = document.createElement('a')
  link.style.display = 'none';
  link.href = '/api/file/show/'+flieitem.saveName;
  link.download = flieitem.showName;
  link.click()
  window.URL.revokeObjectURL(link.href)
} 
//校验
const rules = reactive({
  developArea: [
    { required: true, message: '请输入填报人', trigger: 'blur' },
  ],
  templateId: [
    { required: true, message: '请选择类别', trigger: 'blur' },
  ],
  week: [
    { required: true, message: '请选择季度', trigger: 'change' },
  ],
  year:[
  { required: true, message: '请选择日期', trigger: 'change' },
  ],
  files: [
  { required: true, message: '请上传报表', trigger: 'change' }
  ],
})
//退回和通过参数
const returnInfo: any = ref({
  id: '',
  shResult: '',
  reason: ''
})
//获取报表数据
const getTable = async () => {
  loading.value=true
  // console.log(form.value)
  var res:any = null
  if(userRole.userRole=='1'){
    res = await findListS(form.value);
  }else{
    res = await reportFindList(form.value);
  }
  
  // console.log(res)
if (res.code == 200) {
  tableData.value = res.data.content;
  totals.value = parseInt(res.data.totalElements);
  loading.value=false
}
};

//分页
const handleSizeChange = (val: number) => {
//   console.log(`${val} items per page`)
form.value.pageNum = val;
getTable();
};
const handleCurrentChange = (val: number) => {
//   console.log(`current page: ${val}`)
form.value.currentPage = val;
getTable();
};
//上报
const getReport=async (item:any)=>{
  let res:any=await reportpublish(item.id)
  if(res){
  showSuccess.value = true
  getTable();
  setTimeout(() => {
    showSuccess.value = false
  }, 1500);
  }  
}
//国家级报表修改
const editReport= (row:any)=>{
editInfo.value['id'] = row.id
editInfo.value['name'] = row.name
editShow.value = true
}
//取消修改
const editClear=()=>{
editShow.value = false;
editInfo.value['id'] = ''
editInfo.value['name'] = ''
editInfo.value['files'] = ''
}
const handleFileError = (res: any, fileName: any) => {
if (typeof res.data !== 'undefined') {
  if (res.data.type === 'application/json') {
    const reader = new FileReader();
    reader.onload = function () {
    };
    reader.readAsText(new Blob([res.data]));
  }
} else {
  var downloadUrl = window.URL.createObjectURL(new Blob([res]));
  var a = document.createElement('a');
  a.style.display = 'none';
  a.href = downloadUrl;
  a.download = fileName;
  var event = new MouseEvent('click');
  a.dispatchEvent(event);
}
};
//国家级导入报表
const downSome = ()=>{
upShow.value=true
}
//退回和通过
const returnReport = (val: any, type: any) => {
  returnInfo.value.reason = ""
  returnInfo.value.id = val.checkInfoList[0].id
  returnInfo.value.shResult = type
  if (type == '1') { //通过
    ElMessageBox.confirm(
      '确定通过?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(async () => {
      let res: any = await reportcheck(returnInfo.value)
      if (res.code == 200) {
        ElMessage({
          type: 'success',
          message: '通过成功',
        })
        getTable()
      }
    })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消通过',
        })
      })
  } else {//退回
    returnShow.value = true
  }
}
//确认退回
const sureReturn = () => {
  reportcheck(returnInfo.value).then((res: any) => {
    if (!res) return
    returnShow.value = false
    getTable()
  })
}
const handleExceed: UploadProps['onExceed'] = (files) => {
upload.value!.clearFiles()
const file = files[0] as UploadRawFile
file.uid = genFileId()
upload.value!.handleStart(file)
}
const getFile=(uploadFile:any, uploadFiles:any)=>{
  console.log(uploadFile,upShow.value)
  if(upShow.value){
    upfileInfo.value.files=uploadFile.raw
  }else{
    editInfo.value.files = uploadFile.raw
  }
  
}
//类别选择
const changeTem=(val:any)=>{
  upfileInfo.value.year=""
  upfileInfo.value.week=""
  upfileInfo.value.val=""
}
// 日期选择
const dataChange=(val:string)=>{
//  console.log(val)
 upfileInfo.value.val = val + upfileInfo.value.week
}
//季选择
const changeWeek=(val:any)=>{
upfileInfo.value.val =  upfileInfo.value.year+val
}
//确定上传
const submitForm = async (formEl:any) => {
if (!formEl) return
await formEl.validate(async (valid:any) => {
  if (!valid) return
  let data = new FormData
  console.log(upfileInfo.value)
  data.append('templateId', upfileInfo.value.templateId)
  data.append('developArea', upfileInfo.value.developArea)
  data.append('files', upfileInfo.value.files)
  data.append('val', upfileInfo.value.val) 
  console.log(data)
  let res:any =  await addimports(data)
  console.log(res)
  if(res.code!=='200')return
  ElMessage.success('导入成功！')
  upShow.value=false
  getTable()
})
}
//确定修改
const editSure =async () => {
console.log(editInfo.value)
 if(!editInfo.value.files) return ElMessage.error('请传入文件')
 console.log(editInfo.value)
let data = new FormData
data.append('id', editInfo.value.id)
data.append('files', editInfo.value.files)
let res:any = await editeReport(data)
console.log(res)
if(res.code=='200'){
  ElMessage.success('修改成功')
  getTable()
  editShow.value=false
}
  
}
watch(
  () => router,
  (newValue: any) => {
    // console.log(newValue.currentRoute.value.meta.query)
    upfileInfo.value.templateId =""
    if(newValue.currentRoute.value.meta.templateId=='9'){
      upfileInfo.value.templateId = newValue.currentRoute.value.meta.templateId
      downType.value = newValue.currentRoute.value.meta.query
    }else{
      downType.value = "招商引资数据表"
    }
    form.value.templateType = newValue.currentRoute.value.meta.query
    console.log(downType.value)
    getTable()
  },
  { 
    deep: true,
  immediate:true }
)
onMounted(()=>{
  
})
</script>
<style>
.el-table .warning-row {
--el-table-tr-bg-color: rgba(235, 76, 64, 0.1);
}
</style>
<style lang="scss" scoped>
.showBox {
width: 326px;
height: 208px;
position: fixed;
background-color: white;
box-shadow: 0px 3px 29px 10px #D9D9D9;
left: calc(50% - 163px);
top: calc(50% - 104px);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
font-size: 24px;
font-weight: 500;
z-index: 9999;

img {
  display: block;
  width: 70px;
  height: 70px;
}
}
.pagination-box{
    width: 90%;
    margin: 30px auto;
    ::v-deep(.el-pagination){
      float: right;
    }  
}
.down-bth{
width: 90%;
margin: 20px auto;
}
.data-check{
display: flex;
}
.downMu{
  margin-left: 30px;
}
</style>